from tw import forms
from tw.api import WidgetsList
from tw.forms import PasswordField

from cibynet.model.m_users import UserNewValidator, UserUpdateValidator
from cibynet.model.m_machines import MachineNewValidator
from cibynet.model.m_checks import CheckNewValidator
from cibynet.model import m_banks
from cibynet.model import m_rooms

from cibynet.lib.twforms.forms import ListFieldSet, SimpleForm
from cibynet.model.utils import GetAllObjects

forms.FormField.engine_name = "mako"
forms.InputField.template = "cibynet.lib.twforms.templates.input_field"

# Only for javascript on client side!
object_id_field = forms.HiddenField("object_id")

rooms = GetAllObjects(m_rooms.Room)

class UserNewWidget(ListFieldSet):
  class fields(WidgetsList):
    firstname = forms.TextField()
    lastname = forms.TextField()
    username = forms.TextField()
    email = forms.TextField()
    phonenumber = forms.TextField()
    password = forms.PasswordField()
    passwordconfirmation = PasswordField(label_text="Confirm password")
    room = forms.SingleSelectField(options=[('', '-')] + \
                                          [(str(r.id), r.label) for r in rooms])
  validator = UserNewValidator()
user_new_widget = UserNewWidget("user", strip_name=True, legend="Student")
  
class UserUpdateWidget(UserNewWidget):
  validator = UserUpdateValidator()
user_update_widget = UserUpdateWidget("user", strip_name=True, legend="Student")

class UserNewForm(SimpleForm):
  children = [user_new_widget]
user_new_form = UserNewForm("user", strip_name=True)

class UserUpdateForm(SimpleForm):
  children = [user_update_widget, object_id_field]
  submit_text = "Save"
user_update_form = UserUpdateForm("user", strip_name=True)


banks = GetAllObjects(m_banks.Bank)

class CheckForm(ListFieldSet):
  class fields(WidgetsList):
    checkissuer = forms.TextField()
    checknumber = forms.TextField()
    bank = forms.SingleSelectField(options=[('', '-')] + \
                                           [(b.id, b.name) for b in banks] + \
                                           [('0', 'Other')])
  validator = CheckNewValidator()
  
check_form = CheckForm("check_form")


class MachineWidget(ListFieldSet):
  class fields(WidgetsList):
    hostname = forms.TextField()
    macaddress = forms.TextField()
  validator = MachineNewValidator()

machine_form = MachineWidget("machine_form")


class RegistrationForm(SimpleForm):
  children = [user_new_widget,
              CheckForm("check", strip_name=True, legend='Check'),
              MachineWidget("machine", strip_name=True, legend="Machine"),
              ]
  
registration_form = RegistrationForm("registration")


class ChangeGroupForm(SimpleForm):
  """Form used to add a group to one user.
  """
  fields = [forms.HiddenField('group'), object_id_field]
    
add_group_form = ChangeGroupForm("add_group")
remove_group_form = ChangeGroupForm("remove_group")
  
  